const express = require('express')
const index = express.Router()
const Student = require('../model/user')

index.get('/', (req, res) => {
  res.send('ok')
})
index.get('/add', (req, res) => {
  res.render('index')
})
index.post('/add', async (req, res) => {
  // console.log(req.body)
  try {
    const student = new Student(req.body)
    const result = await student.save()
    console.log('保存成功')
    res.redirect('/list')
  } catch (error) {
    const err = e.errors
    for (const key in err) {
      if (Object.hasOwnProperty.call(err, key)) {
        console.log('保存失败', err[key].message)
      }
    }
  }
})
index.get('/list', async (req, res) => {
  try {
    const students = await Student.find()
    // console.log(students)
    res.render('list', {
      students: students
    })
  } catch (error) {
    console.log('查询失败', error)
  }
})

module.exports = index
